<?php
class Jqcpm extends Controller
{
    
	//关键词自动提交监控
	public function runtask()
    {	
		
		//排名未查的
		$this->nopm();
		
		$w = [
			'status' => ['in',[1,2,3,4,5]],
			//'status' => 1,
			'ybyid' => [['eq',0],['EXP','IS NULL'],'or']
		];
		
		//这里遍历你要查询的关键词
		$tasks = db('kw')->where($w)->field('id,key,domain,sid,status')->limit(100)->select();
		
		foreach($tasks as $t){
			$key = trim($t['key']);
			$key = str_replace(" "," ",$key);//去全角空格
			$domain = trim($t['domain']);
			$sid = $t['sid'];
			
			
			$res = jqcpm_add($sid,$key,$domain);
			$content = json_decode($res);

			if($content->code!=1){
				echo $t['id']." - $key - ".$content->msg." <br>";
			}
			$yid = $content->tid;
			
			$d = [
				'more' => '',
			];
				
			if($t['status']==1){
				$d['status'] = 2;
			}

			if(!$yid){
				$d['status'] = 0;
				$d['more'] = json_decode($addres)->xMessage;
			}else{
				$d['ybyid'] = $yid;
			}

			$w = [
				'id' => $t['id'],
			];

			db('kw')->where($w)->update($d);
			echo $t['id']." - $key - $yid <br>";
		}
		

		return "执行完毕";
    }
	//任务监控消息通知  重点:这个地址请提供给我
    public function notice(){
		$tid = input('tid');
		$rank = input('rank');
		$update_time = input('update_time');
		
	
		$count = db('kw')->where(['ybyid'=>$tid])->update(['xp'=>$rank,'update_time'=>$update_time]);
		if($count==0){
			//判断是否有查询任务
			$w = [
				'ybyid' => $tid,
			];
			$c = db('kw')->where($w)->count();
			if($c==0){jqcpm_del($tid);}
			
		}
		
		return 1;
	}
	
	//排名未查的重查,这个请自动运行,有些词可能会推送失败,要自己手动获取一下
	public function nopm(){
		$h = date('H');
		if($h<9){return "时间未到,9点后执行";}
		//判断是否查询完毕
		$uinfo = jqcpm_uinfo();
		$uinfo2 = json_decode($uinfo);
		$count = $uinfo2->count;
		$c1 = $uinfo2->c1;
		$c2 = $uinfo2->c2;
		
		$c = $c1+$c2;
		if($c>0){
			echo "总词数$count,待推送$c1,待查询$c2<br>";
			return "排名未处理完毕,请等待";
		}
		
		$today = date('Y-m-d');
		
		$w = [
			'status' => ['in',[1,2,3,4,5]], #优化中的
			'ybyid' => ['gt', 0],
			'update_time' => [['elt', $today],['EXP','is null'],'or']
		];
		$c = db('kw')->where($w)->count();
		echo "<br>排名未查总条数:".$c."<br>";
		
		$res = db('kw')->where($w)->limit(200)->column('ybyid');
		
		foreach($res as $r){
			$d = jqcpm_info($r);
			$data = json_decode($d);
			if($data->code==1){
				if(!$data->data->xp){continue;}
				$ybyid = $data->data->id;
                $xp = $data->data->xp;
                $update_time = $data->data->update_time;

				db('kw')->where(['ybyid'=>$ybyid])->update(['xp'=>$xp,'update_time'=>$update_time]);
				echo $ybyid."排名".$xp."已查询,已生成文件$update_time<br>";
			}else{
				$w = [
					'ybyid' => $r,
				];
				$d = [
					'ybyid' => 0,
				];
				db('kw')->where($w)->update($d);
				echo "{$r}查询id不存再,已重置<br>";
			}

		}
		
		return "over";
	}
	
}


